Skip to content

Global Events

In React, we can listen for events on a specific element by passing an attribute:

<form
onSubmit={event => {
// Do something on submit!
}}
>

This is the preferred way to handle events on DOM elements that React produces.

But what if we want to listen to a global event? For example, a scroll event on the window object? For that, we'll need to use the vanilla JS method, addEventListener.

Here's a quick example:

function handleScroll(event) {
console.info('Scroll position:', window.scrollY);
}
window.addEventListener('scroll', handleScroll);

addEventListener takes two arguments:

  1. The event to listen for, as a string.
  2. A function to call when the event occurs.

There are lots of different events we can listen for, including:

  • scroll
  • resize
  • mousemove (and touchmove for touch events)
  • keydown and keyup

De-registering event listeners

When we no longer need to listen for events (eg. when the component unmounts), we can remove the event listener using removeEventListener:

function handleScroll(event) {
console.info('Scroll position:', window.scrollY);
}
// Start listening:
window.addEventListener('scroll', handleScroll);
// Stop listening:
window.removeEventListener('scroll', handleScroll);

It takes the exact same shape as addEventListener.

Note that we need to specify a reference to the same function. For this reason, we can't use an anonymous function:

window.addEventListener('scroll', function(event) {
console.info('Scroll position:', window.scrollY);
});
window.removeEventListener('scroll', ???)

When using an "inline" anonymous or arrow function, we can't reference it later when we need to remove the event listener.